#pragma execution_character_set("utf-8")
#include "database.h"
#include "qualitywidget.h"
#include "ui_qualitywidget.h"

QualityWidget::QualityWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::QualityWidget)
{
    ui->setupUi(this);
     selectrow = 0;

    QStringList header;
    header << "编号" << "名称" << "供应商" << "质检状态" << "图片路径"; // 新增图片路径列
    ui->tableWidget->setColumnCount(5);
    ui->tableWidget->setHorizontalHeaderLabels(header);
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->tableWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->tableWidget->horizontalHeader()->setFixedHeight(50);
    ui->tableWidget->verticalHeader()->setHidden(true);
    ui->tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);
    ui->tableWidget->verticalHeader()->setDefaultSectionSize(50);

    updateDisplay();

  connect(ui->pushButton_back, &QPushButton::clicked, this, &QualityWidget::on_pushButton_back_clicked);
    connect(ui->tableWidget, SIGNAL(cellClicked(int,int)), this, SLOT(onTableClicked(int,int)));
    connect(ui->pushButton_cancel, &QPushButton::clicked, this, &QualityWidget::on_pushButton_cancel_clicked);
}

QualityWidget::~QualityWidget()
{

    delete ui;
}

void QualityWidget::showEvent(QShowEvent *event)
{
    updateDisplay();
    ui->tableWidget->horizontalHeader()->resizeSection(0, ui->tableWidget->width() * 0.15);
    ui->tableWidget->horizontalHeader()->resizeSection(1, ui->tableWidget->width() * 0.25);
    ui->tableWidget->horizontalHeader()->resizeSection(2, ui->tableWidget->width() * 0.3);
    ui->tableWidget->horizontalHeader()->resizeSection(3, ui->tableWidget->width() * 0.3);
}


void QualityWidget::updateDisplay()
{
    ui->tableWidget->clearContents();
    ui->tableWidget->setRowCount(0);

    if (!DataBasePri::database.open()) {
        qCritical() << DataBasePri::database.lastError().text();
        return;
    }

    QSqlQuery query(DataBasePri::database);
    QString sql = R"(
        SELECT o.id, o.name, o.supplier, q.status, q.quality_pic
        FROM orders o
        LEFT JOIN quality q ON o.id = q.order_id
    )";

    if (!query.exec(sql)) {
        qCritical() << query.lastError().text();
        return;
    }

    int row = 0;
    while (query.next()) {
        ui->tableWidget->insertRow(row);
        ui->tableWidget->setItem(row, 0, new QTableWidgetItem(query.value(0).toString())); // id
        ui->tableWidget->setItem(row, 1, new QTableWidgetItem(query.value(1).toString())); // name
        ui->tableWidget->setItem(row, 2, new QTableWidgetItem(query.value(2).toString())); // supplier
        //ui->tableWidget->setItem(row, 3, new QTableWidgetItem(query.value(3).toString())); // status
        ui->tableWidget->setItem(row, 3, new QTableWidgetItem(
            query.value(3).isNull() ? "未质检" : query.value(3).toString()));
        QTableWidgetItem *picItem = new QTableWidgetItem();
        picItem->setData(Qt::UserRole, query.value(4).toString()); // 图片路径
        ui->tableWidget->setItem(row, 4, picItem);

        row++;
    }

    ui->tableWidget->setColumnHidden(4, true);
    DataBasePri::database.close();
}



void QualityWidget::onTableClicked(int row, int /*column*/)
{
    selectrow = row;
    QTableWidgetItem *picItem = ui->tableWidget->item(row, 4);
    QString imagePath = picItem ? picItem->data(Qt::UserRole).toString() : "";

    if (!imagePath.isEmpty() && QFile::exists(imagePath)) {
        QPixmap pix(imagePath);
        ui->label_pic->setPixmap(pix.scaled(ui->label_pic->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
    } else {
        ui->label_pic->clear();  // 或者 ui->label_pic->setText("无图片");
    }
}



void QualityWidget::on_pushButton_pass_clicked()
{
    QString orderId = ui->tableWidget->item(selectrow, 0)->text();
    if (orderId.isEmpty()) return;

    QString filePath = QFileDialog::getOpenFileName(this, "选择质检图片", "", "Images (*.png *.jpg *.jpeg *.bmp)");
    if (filePath.isEmpty()) return;

    QString saveDir = "images";
    QDir().mkpath(saveDir);
    QString destPath = saveDir + "/" + orderId + "_" + QFileInfo(filePath).fileName();
    if (!QFile::copy(filePath, destPath)) {
        QMessageBox::warning(this, "错误", "图片保存失败！");
        return;
    }

    if (!DataBasePri::database.open()) {
        qCritical() << DataBasePri::database.lastError().text();
        return;
    }

    QSqlQuery query(DataBasePri::database);
    bool exists = query.exec(QString("SELECT 1 FROM quality WHERE order_id = '%1'").arg(orderId)) && query.next();
    bool ret = false;

    if (exists) {
        ret = query.exec(QString(
            "UPDATE quality SET status = '通过', quality_pic = '%1' WHERE order_id = '%2'")
            .arg(destPath.replace("'", "''")).arg(orderId));
    } else {
        ret = query.exec(QString(
            "INSERT INTO quality (order_id, status, quality_pic) VALUES ('%1', '通过', '%2')")
            .arg(orderId, destPath.replace("'", "''")));
    }

    DataBasePri::database.close();

    QMessageBox::information(this, "提示", ret ? "质检通过并已保存" : "更新失败");
    updateDisplay();
}



void QualityWidget::on_pushButton_fail_clicked()
{
    QString orderId = ui->tableWidget->item(selectrow, 0)->text();
    if (orderId.isEmpty()) return;

    if (!DataBasePri::database.open()) return;

    QSqlQuery query(DataBasePri::database);
    bool exists = query.exec(QString("SELECT 1 FROM quality WHERE order_id = '%1'").arg(orderId)) && query.next();
    bool ret = false;

    if (exists) {
        ret = query.exec(QString(
            "UPDATE quality SET status = '不合格', quality_pic = '' WHERE order_id = '%1'")
            .arg(orderId));
    } else {
        ret = query.exec(QString(
            "INSERT INTO quality (order_id, status, quality_pic) VALUES ('%1', '不合格', '')")
            .arg(orderId));
    }

    DataBasePri::database.close();

    QMessageBox::information(this, "提示", ret ? "状态已标记为不合格" : "操作失败");
    updateDisplay();
}

void QualityWidget::updateStatus(const QString &status)
{
    QTableWidgetItem *item = ui->tableWidget->item(selectrow, 0);
    QString orderId = item->text();

    if (!DataBasePri::database.open()) {
        qCritical() << DataBasePri::database.lastError().text();
        return;
    }

    QSqlQuery query(DataBasePri::database);
    bool ret = query.exec(QString("UPDATE orders SET status = '%1' WHERE id = '%2'")
                          .arg(status).arg(orderId));
    DataBasePri::database.close();

    if (ret) {
        QMessageBox::information(this, "提示", "状态更新成功");
    } else {
        QMessageBox::warning(this, "提示", "状态更新失败");
    }

    updateDisplay();
}


void QualityWidget::on_pushButton_cancel_clicked()
{
    QString orderId = ui->tableWidget->item(selectrow, 0)->text();
    if (orderId.isEmpty()) return;

    if (!DataBasePri::database.open()) {
        qCritical() << DataBasePri::database.lastError().text();
        return;
    }

    QSqlQuery query(DataBasePri::database);
    QString oldPath;

    // 查询是否已有质检记录
    bool exists = false;
    if (query.exec(QString("SELECT quality_pic FROM quality WHERE order_id = '%1'").arg(orderId)) && query.next()) {
        exists = true;
        oldPath = query.value(0).toString();
    }

    bool ret = false;
    if (exists) {
        // 已存在：更新记录
        ret = query.exec(QString("UPDATE quality SET status = '未质检', quality_pic = '' WHERE order_id = '%1'").arg(orderId));
    } else {
        // 不存在：插入新记录
        ret = query.exec(QString("INSERT INTO quality (order_id, status, quality_pic) VALUES ('%1', '未质检', '')").arg(orderId));
    }

    DataBasePri::database.close();

    if (ret) {
        if (!oldPath.isEmpty() && QFile::exists(oldPath)) {
            QFile::remove(oldPath);
        }
        QMessageBox::information(this, "提示", "质检信息已撤销，状态设为未质检");
    } else {
        QMessageBox::warning(this, "提示", "撤销失败");
    }

    ui->label_pic->clear();
    updateDisplay();
}



void QualityWidget::on_pushButton_back_clicked()
{
    emit sendDisWidget("m_AdminWidget");
}
